package com.yunfinal.api.service.db.dao;

import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;

/**
 * 生成dao代码
 * @author 杜福忠
 */
public class GenerateDao {
    protected Template template;
    public String templateName;
    public String name;
    public String tableName;
    public String className;
    public String nameKey;
    public String basePath;
    public String pathStr;

    public GenerateDao init(String basePath, String name, String tableName, String nameKey) {
        this.name = name;
        this.tableName = tableName;
        this.nameKey = nameKey;
        this.basePath = basePath.replace("\\\\", "/");
        initClassName();
        initPathStr();
        this.templateName = "/generate/GenerateDao.jf";
        initTemplate();
        return this;
    }

    protected void initPathStr() {
        this.pathStr = this.basePath + "/com/momathink/miniapp/common/dao/" + this.className + ".java";
    }

    protected void initClassName() {
        this.className = StrKit.toCamelCase(this.tableName);
        this.className = StrKit.firstCharToUpperCase(this.className);
        this.className = "Dao".concat(this.className);
    }

    protected void initTemplate() {
        Engine engine = new Engine(GenerateDao.class.getName());
        engine.addSharedMethod(new StrKit());
        engine.setToClassPathSourceFactory();
        this.template = engine.getTemplate(templateName);
    }

    public void run (){
        System.out.println(pathStr);
        template.render(Kv.by("d", this), pathStr);
        System.out.println(toString());
    }

    @Override
    public String toString() {
        return "GenerateDao{" +
                "templateName='" + templateName + '\'' +
                ", name='" + name + '\'' +
                ", tableName='" + tableName + '\'' +
                ", className='" + className + '\'' +
                ", nameKey='" + nameKey + '\'' +
                ", basePath='" + basePath + '\'' +
                ", pathStr='" + pathStr + '\'' +
                '}';
    }
}
